package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.RedisConstant;
import com.itheima.dao.MemberDao;
import com.itheima.dao.OrderDao;
import com.itheima.dao.SetMealDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Address;
import com.itheima.pojo.InterventionSetmeal;
import com.itheima.pojo.Order;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetMealService;
import com.itheima.utils.DateUtils;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.JedisPool;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = SetMealService.class)
@Transactional
public class SetMealServiceImpl implements SetMealService {
    @Autowired
    private OrderDao orderDao;
    @Autowired
    private SetMealDao setMealDao;
    @Autowired
    private JedisPool jedisPool;
    @Autowired
    private MemberDao memberDao;
    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;
    @Value("${out_put_path}")
    private String outPutPath;//从属性文件中读取要生成的html对应的目录

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        Page<Setmeal> page = setMealDao.findPage(queryPageBean.getQueryString());
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 新增套餐信息,同时关联检查组
     *
     * @param setmeal
     * @param checkgroupIds
     */
    @Override
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        //新增套餐信息
        setMealDao.add(setmeal);
        Integer id = setmeal.getId();
        setSetMealAndCheckGroup(id,checkgroupIds);
        //将图片名称保存到jedis集合中
        String img = setmeal.getImg();
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,img);

        //当添加套餐后需要重新生成静态页面（套餐列表页面、套餐详情页面）
        generateMobileStaticHtml();
    }

    //生成当前方法所需的静态页面
    public void generateMobileStaticHtml(){
        //在生成静态页面之前需要查询数据
        List<Setmeal> list = setMealDao.getSetmeal();

        //需要生成套餐列表静态页面
        generateMobileSetmealListHtml(list);

        //需要生成套餐详情静态页面
        generateMobileSetmealDetailHtml(list);
    }

    //生成套餐列表静态页面
    public void generateMobileSetmealListHtml(List<Setmeal> list){
        Map map = new HashMap();
        //为模板提供数据，用于生成静态页面
        map.put("setmealList",list);
        generteHtml("mobile_setmeal.ftl","m_setmeal.html",map);
    }

    //生成套餐详情静态页面（可能有多个）
    public void generateMobileSetmealDetailHtml(List<Setmeal> list){
        for (Setmeal setmeal : list) {
            Map map = new HashMap();
            map.put("setmeal",setMealDao.findAllById(setmeal.getId()));
            generteHtml("mobile_setmeal_detail.ftl","setmeal_detail_" + setmeal.getId() + ".html",map);
        }
    }

    //通用的方法，用于生成静态页面
    public void generteHtml(String templateName,String htmlPageName,Map map){
        Configuration configuration = freeMarkerConfigurer.getConfiguration();//获得配置对象
        Writer out = null;
        try {
            Template template = configuration.getTemplate(templateName);
            //构造输出流
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(outPutPath + "/" + htmlPageName)), StandardCharsets.UTF_8));
            //输出文件
            template.process(map,out);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    public List<Setmeal> getSetmeal() {
        return setMealDao.getSetmeal();
    }

    @Override
    public Setmeal findAllById(Integer id) {
        return setMealDao.findAllById(id);
    }

    @Override
    public List<Integer> findCheckGroupIdsBySeatMealId(Integer id) {
        return setMealDao.findCheckGroupIdsBySeatMealId(id);
    }

    @Override
    public List<Map<String, Object>> findSetmealCount() {
        return setMealDao.findSetmealCount();
    }

    @Override
    public List<Setmeal> findAllSetmeal() {
        return setMealDao.findAllSetmeal();
    }

    @Override
    public List<Map<String, Object>> findSetmealPrice(String startDate, String endDate) {
        return setMealDao.findSetmealPrice(startDate, endDate);
    }


    //添加中间关系表关联关系
    public void setSetMealAndCheckGroup(Integer id, Integer[] checkgroupIds) {
        if (checkgroupIds != null && checkgroupIds.length > 0) {
            HashMap<String, Integer> map = new HashMap<>();
            for (Integer checkgroupId : checkgroupIds) {
                map.put("setmealid",id);
                map.put("checkgroupId",checkgroupId);
                setMealDao.setSetMealAndCheckGroup(map);
            }
        }
    }

    //根据日期模糊查询
    @Override
    public List<InterventionSetmeal> findByDate(Map map, String telephone) {
        map.put("telephone",telephone);
        return setMealDao.findByDate(map);
    }

    @Override
    public Map<String, Object> findBySetmealId(Integer oid, String telephone) {
        Map<String,Object> map= orderDao.findByOrderId(oid);


        return null;
    }

    @Override
    public Map<String, Object> findByOId(Integer oid) {
        Map<String,Object> map=setMealDao.findByOId(oid);
        Integer interventionId =(Integer) map.get("interventionId") ;
        List<String> sports=setMealDao.findSportsByinterventionId(interventionId);
        String sportsStr = sports.toString();
        List<String> foods=setMealDao.findFoodsByinterventionId(interventionId);
        String foodsStr = foods.toString();
        map.put("m2_name",sportsStr);
        map.put("d_name",foodsStr);
        return map;
    }

    @Override
    public List<InterventionSetmeal> getSetmealByPhone(String telephone)  {
        return setMealDao.getSetmealByPhone(telephone);
    }
}
